<template>
    <div class="app-container">
        <!-- 操作面板 -->
        <el-card class="operation-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <span class="card-title">课程任务管理操作</span>
                </div>
            </template>
            
            <!-- 文件操作区域 -->
            <div class="operation-section">
                <div class="section-title">文件操作</div>
                <div class="button-group">
                    <el-upload 
                        ref="uploadRef" 
                        accept=".xls,.xlsx" 
                        action="/api/uploadTask" 
                        :on-remove="handleRemove"
                        :on-error="handleError" 
                        :on-success="uploadSuccess" 
                        :disabled="importBtnDisabled" 
                        :file-list="fileList"
                        :auto-upload="false" 
                        :limit="1"
                        class="upload-component"
                    >
                        <template #trigger>
                            <el-button type="primary" :icon="UploadFilled">
                                从Excel导入
                            </el-button>
                        </template>
                        <el-button type="success" :loading="loading" @click="submitUpload" :icon="Upload">
                            上传到服务器
                        </el-button>
                        
                    </el-upload>

                    <el-button type="info" @click="downloadTemplate()" :icon="Download">
                        下载模板
                    </el-button>

                    <div class="upload-tip">
                                只能上传xls/xlsx文件，导入新班级后将清空原来的班级，请一次性将本学期班级导入完毕
                    </div>
                </div>
            </div>
            
            <!-- 数据操作区域 -->
            <div class="operation-section">
                <div class="section-title">数据操作</div>
                <div class="button-group">
                    <el-button type="primary" @click="handleAdd" :icon="Plus">
                        新增任务
                    </el-button>
                    <el-button 
                        type="danger" 
                        @click="handleBatchDelete" 
                        :disabled="multipleSelection.length === 0"
                        :icon="Delete"
                    >
                        批量删除 ({{ multipleSelection.length }})
                    </el-button>
                </div>
            </div>
        </el-card>

        <!-- 展示上传后的结果 -->
        <el-table v-loading="listLoading" :data="paginatedList" element-loading-text="Loading" border fit
            highlight-current-row @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            
            <el-table-column align="center" label="序号" width="60px">
                <template #default="scope">
                    {{ scope.$index + 1 + (currentPage - 1) * pagesize }}
                </template>
            </el-table-column>

            <el-table-column label="课程编号" prop="courseNo" align="center">
                <template #default="scope">
                    {{ scope.row.courseNo }}
                </template>
            </el-table-column>
            <el-table-column label="课程名" prop="courseName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.courseName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="班级编号" prop="classNo" align="center">
                <template #default="scope">
                    {{ scope.row.classNo }}
                </template>
            </el-table-column>
            <el-table-column label="教师编号" prop="teacherNo" align="center">
                <template #default="scope">
                    <span>{{ scope.row.teacherNo }}</span>
                </template>
            </el-table-column>
            <el-table-column label="教师姓名" prop="teacherName" align="center">
                <template #default="scope">
                    {{ scope.row.teacherName }}
                </template>
            </el-table-column>
            <el-table-column label="周学时" prop="weeksNumber" align="center">
                <template #default="scope">
                    <span>{{ scope.row.weeksNumber }}</span>
                </template>
            </el-table-column>
            <el-table-column label="周数" prop="weeksSum" align="center">
                <template #default="scope">
                    {{ scope.row.weeksSum }}
                </template>
            </el-table-column>
            <el-table-column label="课程属性" prop="courseAttr" align="center">
                <template #default="scope">
                    <span>{{ scope.row.courseAttr }}</span>
                </template>
            </el-table-column>
            
            <el-table-column label="操作" align="center" width="200px">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 1rem; margin-left: 0.4rem" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]"
            :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="list.length">
        </el-pagination>
        
        <!-- 新增/编辑对话框 -->
        <el-dialog
            :title="dialogTitle"
            v-model="dialogVisible"
            width="900px"
            :before-close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="120px"
            >
                <!-- 基本信息 -->
                <el-divider content-position="left">基本信息</el-divider>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="课程编号" prop="courseNo">
                            <el-select v-model="form.courseNo" placeholder="请选择课程" filterable clearable @change="onCourseChange">
                                <el-option
                                    v-for="item in courseList"
                                    :key="item.courseNo"
                                    :label="`${item.courseNo} - ${item.courseName}`"
                                    :value="item.courseNo">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="课程名称" prop="courseName">
                            <el-input v-model="form.courseName" placeholder="课程名称" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="课程属性" prop="courseAttr">
                            <el-select v-model="form.courseAttr" placeholder="请选择课程属性">
                                <el-option label="理论课" value="01"></el-option>
                                <el-option label="实验课" value="02"></el-option>
                                <el-option label="实践课" value="03"></el-option>
                                <el-option label="体育课" value="04"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <!-- 班级和教师信息 -->
                <el-divider content-position="left">班级和教师</el-divider>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="班级编号" prop="classNo">
                            <el-select v-model="form.classNo" placeholder="请选择班级" filterable clearable @change="onClassChange">
                                <el-option
                                    v-for="item in classList"
                                    :key="item.classNo"
                                    :label="`${item.classNo} - ${item.className}`"
                                    :value="item.classNo">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级名称" prop="className">
                            <el-input v-model="form.className" placeholder="班级名称" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                         <el-form-item label="班级数量" prop="classCount">
                             <el-select v-model="form.classCount" placeholder="同时上课班级数">
                                 <el-option label="1个班级" value="1"></el-option>
                                 <el-option label="2个班级" value="2"></el-option>
                                 <el-option label="3个班级" value="3"></el-option>
                                 <el-option label="4个班级" value="4"></el-option>
                                 <el-option label="5个班级" value="5"></el-option>
                             </el-select>
                         </el-form-item>
                     </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="教师编号" prop="teacherNo">
                            <el-select v-model="form.teacherNo" placeholder="请选择教师" filterable clearable @change="onTeacherChange">
                                <el-option
                                    v-for="item in teacherList"
                                    :key="item.teacherNo"
                                    :label="`${item.teacherNo} - ${item.teacherName}`"
                                    :value="item.teacherNo">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="教师姓名" prop="teacherName">
                            <el-input v-model="form.teacherName" placeholder="教师姓名" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="教学区域" prop="areaNo">
                            <el-select v-model="form.areaNo" placeholder="请选择教学区域">
                                <el-option label="精工楼" value="01"></el-option>
                                <el-option label="明理楼" value="02"></el-option>
                                <el-option label="逸夫楼" value="03"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <!-- 时间安排 -->
                <el-divider content-position="left">时间安排</el-divider>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="开始周" prop="startWeek">
                            <el-input-number v-model="form.startWeek" :min="1" :max="20" placeholder="开始周"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结束周" prop="endWeek">
                            <el-input-number v-model="form.endWeek" :min="1" :max="20" placeholder="结束周"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单双周" prop="biweekly">
                            <el-select v-model="form.biweekly" placeholder="请选择单双周">
                                <el-option label="非单双周" value="0"></el-option>
                                <el-option label="单周" value="1"></el-option>
                                <el-option label="双周" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="周学时" prop="weeksNumber">
                            <el-input-number v-model="form.weeksNumber" :min="2" :max="20" :step="2" placeholder="必须是2的倍数"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="总周数" prop="weeksSum">
                            <el-input-number v-model="form.weeksSum" :min="1" :max="20" placeholder="总周数"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Upload, UploadFilled, Download, Plus, Delete } from '@element-plus/icons-vue';
import axios from 'axios';

const list = ref([]);
const listLoading = ref(true);
const currentPage = ref(1);
const pagesize = ref(8);
const fileList = ref([]);
const loading = ref(false);
const importBtnDisabled = ref(false);
const uploadRef = ref(null);

// 多选相关
const multipleSelection = ref([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);

// 班级、教师和课程列表
const classList = ref([]);
const teacherList = ref([]);
const courseList = ref([]);
const form = ref({
    id: null,
    courseNo: '',
    courseName: '',
    classNo: '',
    className: '',
    teacherNo: '',
    teacherName: '',
    courseAttr: '',
    startWeek: 1,
    endWeek: 16,
    biweekly: '0',
    areaNo: '',
    classCount: '1',
    weeksNumber: 2,
    weeksSum: 16
});

// 表单验证规则
const rules = {
    courseNo: [{ required: true, message: '请选择课程', trigger: 'change' }],
    courseName: [{ required: true, message: '课程名称不能为空', trigger: 'blur' }],
    classNo: [{ required: true, message: '请选择班级', trigger: 'change' }],
    className: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
    teacherNo: [{ required: true, message: '请选择教师', trigger: 'change' }],
    teacherName: [{ required: true, message: '教师姓名不能为空', trigger: 'blur' }],
    courseAttr: [{ required: true, message: '请选择课程属性', trigger: 'change' }],
    startWeek: [{ required: true, message: '请输入开始周', trigger: 'blur' }],
    endWeek: [{ required: true, message: '请输入结束周', trigger: 'blur' }],
    biweekly: [{ required: true, message: '请选择单双周', trigger: 'change' }],
    areaNo: [{ required: true, message: '请选择教学区域', trigger: 'change' }],
    classCount: [{ required: true, message: '请选择班级数量', trigger: 'change' }],
    weeksNumber: [
        { required: true, message: '请输入周学时', trigger: 'blur' },
        { 
            validator: (rule, value, callback) => {
                if (value && value % 2 !== 0) {
                    callback(new Error('周学时必须是2的倍数'));
                } else {
                    callback();
                }
            }, 
            trigger: 'blur' 
        }
    ],
    weeksSum: [{ required: true, message: '请输入总周数', trigger: 'blur' }]
};

// 计算属性，用于分页
const paginatedList = computed(() => {
    if (!list.value) return [];
    return list.value.slice((currentPage.value - 1) * pagesize.value, currentPage.value * pagesize.value);
});

const getList = async () => {
    listLoading.value = true;
    try {
        const response = await axios.get('/api/task/getList',{
          headers: {
            "token": localStorage.getItem("token"),
          },
        });
        list.value = response.data.data || []; // 确保 response.data.data 存在
        if (list.value.length === 0) {
            ElMessage({ message: '暂无排课任务', type: 'success' });
        }
    } catch (error) {
        console.error('Error fetching list:', error);
        ElMessage({ message: '获取列表失败', type: 'error' });
    } finally {
        listLoading.value = false;
    }
};

// 下载模板
const downloadTemplate = () => {
    window.location.href = '/api/downloadTask'; // 保持不变，或者用更安全的方式处理下载
};

// 上传成功
const uploadSuccess = (response, file, uploadedFileList) => {
    loading.value = false;
    getList(); // 重新获取列表
    ElMessage({ message: '上传成功', type: 'success' });
    fileList.value = []; // 清空已上传文件列表，以便下次上传
    if (uploadRef.value) {
        uploadRef.value.clearFiles(); // 清空el-upload组件内部的文件列表
    }
};

const handleRemove = (file, uploadedFileList) => {
    // console.log('Removed file:', file, uploadedFileList);
    // 如果需要，可以在这里处理文件移除后的逻辑
};

const handleError = (error, file, uploadedFileList) => {
    loading.value = false;
    console.error('Upload error:', error);
    // Element Plus 的 error 类型通常是一个 Error 对象，而不是字符串
    // 如果 error.message 存在，则显示它，否则显示通用消息
    const errorMessage = error instanceof Error ? error.message : '文件上传失败';
    ElMessage({ message: errorMessage, type: 'error' });
    if (uploadRef.value) {
        uploadRef.value.clearFiles();
    }
};

// 提交上传文件事件
const submitUpload = () => {
    if (uploadRef.value) {
        loading.value = true;
        uploadRef.value.submit();
    } else {
        ElMessage({ message: '上传组件未准备好', type: 'warning' });
    }
};

const handleSizeChange = (val) => {
    pagesize.value = val;
    // currentPage.value = 1; // 通常改变每页数量时，会回到第一页
    // console.log(`每页 ${val} 条`);
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
};

// 多选处理
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 新增任务
const handleAdd = () => {
    dialogTitle.value = '新增任务';
    resetForm();
    dialogVisible.value = true;
};

// 编辑任务
const handleEdit = (row) => {
    dialogTitle.value = '编辑任务';
    form.value = { ...row };
    dialogVisible.value = true;
};

// 删除单个任务
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm('此操作将永久删除该任务, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        
        const response = await axios.delete(`/api/task/delete/${row.id}`, {
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        
        if (response.data.code === 200) {
            ElMessage({ message: '删除成功', type: 'success' });
            getList();
        } else {
            ElMessage({ message: response.data.message || '删除失败', type: 'error' });
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error);
            ElMessage({ message: '删除失败', type: 'error' });
        }
    }
};

// 批量删除
const handleBatchDelete = async () => {
    if (multipleSelection.value.length === 0) {
        ElMessage({ message: '请选择要删除的任务', type: 'warning' });
        return;
    }
    
    try {
        await ElMessageBox.confirm(`此操作将永久删除选中的${multipleSelection.value.length}个任务, 是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        
        const ids = multipleSelection.value.map(item => item.id);
        const response = await axios.delete('/api/task/deleteBatch', {
            data: ids,
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        
        if (response.data.code === 200) {
            ElMessage({ message: '批量删除成功', type: 'success' });
            getList();
            multipleSelection.value = [];
        } else {
            ElMessage({ message: response.data.message || '批量删除失败', type: 'error' });
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error);
            ElMessage({ message: '批量删除失败', type: 'error' });
        }
    }
};

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;
    
    try {
        await formRef.value.validate();
        
        const url = form.value.id ? '/api/task/update' : '/api/task/add';
        const method = form.value.id ? 'put' : 'post';
        
        const response = await axios[method](url, form.value, {
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        
        if (response.data.code === 200) {
            ElMessage({ message: form.value.id ? '更新成功' : '新增成功', type: 'success' });
            dialogVisible.value = false;
            getList();
        } else {
            ElMessage({ message: response.data.message || '操作失败', type: 'error' });
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage({ message: '操作失败', type: 'error' });
    }
};

// 重置表单
const resetForm = () => {
    form.value = {
        id: null,
        courseNo: '',
        courseName: '',
        classNo: '',
        className: '',
        teacherNo: '',
        teacherName: '',
        courseAttr: '',
        startWeek: 1,
        endWeek: 16,
        biweekly: '0',
        areaNo: '',
        classCount: '1',
        weeksNumber: 2,
        weeksSum: 16
    };
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false;
    resetForm();
};

// 获取班级列表
const getClassList = async () => {
    try {
        const response = await axios.get('/api/classes/getList', {
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        classList.value = response.data.data || [];
    } catch (error) {
        console.error('获取班级列表失败:', error);
        ElMessage({ message: '获取班级列表失败', type: 'error' });
    }
};

// 获取教师列表
const getTeacherList = async () => {
    try {
        const response = await axios.get('/api/teacher/getList', {
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        teacherList.value = response.data.data || [];
    } catch (error) {
        console.error('获取教师列表失败:', error);
        ElMessage({ message: '获取教师列表失败', type: 'error' });
    }
};

// 获取课程列表
const getCourseList = async () => {
    try {
        const response = await axios.get('/api/course/getList', {
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        courseList.value = response.data.data || [];
    } catch (error) {
        console.error('获取课程列表失败:', error);
        ElMessage({ message: '获取课程列表失败', type: 'error' });
    }
};

// 课程选择变化事件
const onCourseChange = (courseNo) => {
    if (courseNo) {
        const selectedCourse = courseList.value.find(item => item.courseNo === courseNo);
        if (selectedCourse) {
            form.value.courseName = selectedCourse.courseName;
            form.value.courseAttr = selectedCourse.courseAttr;
        }
    } else {
        form.value.courseName = '';
        form.value.courseAttr = '';
    }
};

// 班级选择变化事件
const onClassChange = (classNo) => {
    if (classNo) {
        const selectedClass = classList.value.find(item => item.classNo === classNo);
        if (selectedClass) {
            form.value.className = selectedClass.className;
        }
    } else {
        form.value.className = '';
    }
};

// 教师选择变化事件
const onTeacherChange = (teacherNo) => {
    if (teacherNo) {
        const selectedTeacher = teacherList.value.find(item => item.teacherNo === teacherNo);
        if (selectedTeacher) {
            form.value.teacherName = selectedTeacher.teacherName;
        }
    } else {
        form.value.teacherName = '';
    }
};

onMounted(() => {
    getList();
    getClassList();
    getTeacherList();
    getCourseList();
});

</script>

<style scoped>
.app-container {
    padding: 20px;
}

.operation-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.operation-section {
    margin-bottom: 20px;
}

.operation-section:last-child {
    margin-bottom: 0;
}

.section-title {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
}

.button-group {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: center;
}

.upload-component {
    display: flex;
    align-items: center;
    gap: 8px;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
    margin-top: 8px;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border-left: 3px solid #409eff;
}

.el-button {
    border-radius: 6px;
}

.el-card {
    border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .button-group {
        flex-direction: column;
        align-items: stretch;
    }
    
    .upload-component {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>